package org.sraosha.framework.handler.exception;

import org.sraosha.framework.dto.ApiResult;
import org.sraosha.framework.enumeration.ApiResultEnum;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理规则降级的统一异常类
 */
@Slf4j
public class CustomBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        ApiResult apiResult = null;
        if (e instanceof FlowException) {
            apiResult = ApiResult.error(ApiResultEnum.INTERFACE_RESTRICTED.getCode(), ApiResultEnum.INTERFACE_RESTRICTED.getMessage());
        }
        if (e instanceof DegradeException) {
            apiResult = ApiResult.error(ApiResultEnum.SERVICE_DEGRADED.getCode(), ApiResultEnum.SERVICE_DEGRADED.getMessage());
        }
        if (e instanceof ParamFlowException) {
            apiResult = ApiResult.error(ApiResultEnum.HOTSPOT_PARAMETER_RESTRICTED.getCode(), ApiResultEnum.HOTSPOT_PARAMETER_RESTRICTED.getMessage());
        }
        if (e instanceof SystemBlockException) {
            apiResult = ApiResult.error(ApiResultEnum.TRIGGER_SYSTEM_PROTECTION_RULE.getCode(), ApiResultEnum.TRIGGER_SYSTEM_PROTECTION_RULE.getMessage());
        }
        if (e instanceof AuthorityException) {
            apiResult = ApiResult.error(ApiResultEnum.UNAUTHORIZED.getCode(), ApiResultEnum.UNAUTHORIZED.getMessage());
        }
        httpServletResponse.setStatus(HttpStatus.SERVICE_UNAVAILABLE.value());
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(httpServletResponse.getWriter(), apiResult);
    }
}
